﻿using System.ComponentModel.Composition;
using Cubicle.Core.Interfaces;
using Cubicle.Core.Shared;

namespace Cubicle.Core.Processors.Invoke
{
    [Export("Cubicle.Processors.Invoke.ClassificationProcessor", typeof(IProcessor<InstructionRequest>))]
    [ExportMetadata("Name", "ClassificationProcessor")]
    [ExportMetadata("Description", "Classifies an instruction as 'construct' / 'custom construct' / 'other'")]
    public class ClassificationProcessor : InstructionRequestProcessor
    {

        public const string ConstructId = ".ctor";
        public const string CustomConstructId = ".ctorc";

        #region Overrides of Processor

        public ClassificationProcessor() : base(RequestType.AllIncoming) { }

        public override InstructionRequest ConditionalProcess(InstructionRequest request)
        {
            request.IsGenericMethodInvoke = request.Inst.MethodArgs != null && request.Inst.MethodArgs.Length > 0;
            request.ParameterCount = request.Inst.Parameters == null
                ? 0
                : request.Inst.Parameters.Length;
            var memberName = request.Inst.MemberName;
            switch (memberName)
            {
                case ConstructId:
                    request.Type(RequestType.Construct);
                    break;
                case CustomConstructId:
                    request.Type(RequestType.CustomConstruct);
                    request.TargetType = TypeCache.GetType(request.Inst.Handle);
                    break;
                default:
                    request.Type(request.Type().Subtract(RequestType.Construct | RequestType.CustomConstruct));
                    break;
            }
            return request;
        }

        #endregion
    }
}